package dao;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import utils.DBUtils;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;

public abstract class BaseDao {
    QueryRunner queryRunner = new QueryRunner();


    public <T> T queryForOne(Class<T> tClass, String sql, Object... args) {
        Connection connection = DBUtils.getConnection();

        try {
            return queryRunner.query(connection, sql, new BeanHandler<>(tClass), args);
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }finally {
            DBUtils.close(connection);
        }
    }


    public <T> ArrayList<T> queryForList(Class<T> tClass, String sql, Object... args) {
        Connection connection = DBUtils.getConnection();
        try {
            return new ArrayList<>(queryRunner.query(connection, sql, new BeanListHandler<>(tClass), args));
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }finally {
            DBUtils.close(connection);
        }
    }

    public int update(String sql, Object... args) {
        Connection connection = DBUtils.getConnection();
        try {
            return queryRunner.update(connection, sql, args);
        } catch (SQLException e) {
            e.printStackTrace();
            return -1;
        }finally {
            DBUtils.close(connection);
        }
    }

    public Object queryForSingleValue(String sql, Object... args) {
        Connection connection = DBUtils.getConnection();
        try {
            return queryRunner.query(connection, sql, new ScalarHandler(), args);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtils.close(connection);
        }
        return null;
    }

}
